package com.zjlanyun.erp.interior.production;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.aihook.alertview.library.AlertView;
import com.aihook.alertview.library.OnItemClickListener;
import com.alibaba.fastjson.JSON;
import com.yolanda.nohttp.rest.Response;
import com.zjlanyun.erp.Data;
import com.zjlanyun.erp.R;
import com.zjlanyun.erp.network.WebApi;
import com.zjlanyun.erp.nohttp.HttpRequest;
import com.zjlanyun.erp.nohttp.SimpleHttpListener;
import com.zjlanyun.erp.rfid.m10.u8.activity.OutPowerActivity;
import com.zjlanyun.erp.utils.Toastor;
import com.zjlanyun.erp.utils.ViewUtil;
import com.zjlanyun.erp.view.BaseRFIDActivity;

import org.json.JSONObject;

import java.util.HashMap;

import butterknife.Bind;
import butterknife.OnClick;

public class PutInStorage extends BaseRFIDActivity {

    @Bind(R.id.tv_epc) TextView tv_epc;
    @Bind(R.id.et_FNumber) EditText et_FNumber;
    @Bind(R.id.et_FCLQty) EditText et_FCLQty;
    @Bind(R.id.et_FQty) EditText et_FQty;

    @Bind(R.id.tv_result) TextView tv_result;
    @Bind(R.id.tv_status) TextView tv_status;
    @Bind(R.id.ll_submit) LinearLayout ll_submit;

    private boolean scaning = false;
    private String apiUrl = "";
    private String epc = "";
    private String flag = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.put_in_storage);
        initBaseView();
        initView();
    }

    private void initView() {
        Bundle bundle = getIntent().getExtras();
        title.setText(bundle.getString("title"));
        if (bundle.getString("title").equals("原料入库")){
            flag = "yuanliao";
        } else if (bundle.getString("title").equals("成品入库")) {
            flag = "chengpin";
        } else if (bundle.getString("title").equals("销售退货")) {
            flag = "tuihuo";
        }
        apiUrl = WebApi.production();
        ll_submit.setVisibility(View.VISIBLE);
    }

    /**
     * 开始扫描
     */
    public void startScan() {
        tv_status.setText("盘询开始");
        scanNumber = 1;
        scaning = true;
        super.startScan();
    }

    /**
     * 停止扫描
     */
    public void stopScan() {
        tv_status.setText("盘询结束");
        scaning = false;
        super.stopScan();
    }

    public void refreshText() {
        super.refreshText();
        tv_result.setText(String.format("扫描到:%d个", m_curInventoryBuffer.lsTagList.size()));
        if (m_curInventoryBuffer.lsTagList.size() > 0) {
            epc = m_curInventoryBuffer.lsTagList.get(0).getStrEPC().replace(" ", "");
            getProductInfo();
        }
    }

    private void getProductInfo(){
        HashMap<String, Object> param = new HashMap<>();
        param.put("epc", epc);
        HttpRequest client = new HttpRequest(mContext, apiUrl, "getProductInfo", JSON.toJSONString(param), true, true);
        client.send(new SimpleHttpListener<JSONObject>() {
            @Override
            public void onSucceed(int what, Response<JSONObject> response) {
                JSONObject data = response.get().optJSONObject("data");
                if (data.optInt("FCLItemID") > 0 || data.optInt("FItemID") > 0) {
                    Toastor.getInstance().showShortToast("该卡已绑定了产品");
                    tv_epc.setText("");
                } else {
                    tv_epc.setText(data.optString("epc"));
                }
            }

            @Override
            public void onError(int what, Response<JSONObject> response) {
                clean();
            }
        });
    }

    //提交
    @OnClick(R.id.ll_submit)
    public void putInStorage(){
        ViewUtil.hideInputMethod(mContext, ll_submit);
        if (et_FNumber.getText().toString().equals("")) {
            Toastor.getInstance().showShortToast("请输入物料代码");
            return;
        }
        HashMap<String, Object> param = new HashMap<>();
        param.put("epc", epc);
        param.put("Flag", flag);
        param.put("FNumber", et_FNumber.getText().toString().trim());
        param.put("FCLQty", et_FCLQty.getText().toString());
        param.put("FQty", et_FQty.getText().toString());
        final HttpRequest client = new HttpRequest(mContext, apiUrl, "putInStorage", JSON.toJSONString(param), true, true);
        client.send(new SimpleHttpListener<JSONObject>() {
            @Override
            public void onSucceed(int what, Response<JSONObject> response) {
                Toastor.getInstance().showShortToast(R.string.submit_success);
                clean();
            }
        });
    }

    private void clean(){
        tv_epc.setText("");
        et_FNumber.setText("");
        et_FCLQty.setText("");
        et_FQty.setText("");
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == 80 && Build.MODEL.equals(Data.RFID_DEVICE)) {
            if (scaning) {
                stopScan();
            } else {
                startScan();
            }
            return false;
        } else if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            if (!tv_epc.getText().toString().equals("")) {
                new AlertView("提示", "有未提交的数据，确定退出当前页吗？", "取消", new String[]{"确定"}, null, mContext, AlertView.Style.AlertDialog, new OnItemClickListener() {
                    @Override
                    public void onItemClick(Object o, int position) {
                        if (position == 0) {
                            finish();
                        }
                    }
                }).show();
                return false;
            }
        }  else if ((keyCode == 131 && Build.MODEL.equals(Data.RFID_DEVICE)) || (keyCode == 132 && Build.MODEL.equals(Data.RFID_DEVICE)) || (keyCode == 133 && Build.MODEL.equals(Data.RFID_DEVICE))) {
            Intent intent = new Intent(mContext, OutPowerActivity.class);
            intent.putExtra("from", "RFID" + className);
            startActivity(intent);
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

}
